package com.ryan.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;

import com.ryan.notify.R;

public class ScanView extends View{

	private static final int STEP=2;
	
	private Bitmap mScaned;
	private Bitmap mUnscan;
	private Bitmap mScanline;
	
	private int mPos;
	private Rect mRect;
	private boolean mIsDown;
	private boolean mIsEnd;
	
	
	public ScanView(Context context){
		this(context,null,0);
	}
	public ScanView(Context context, AttributeSet attrs){
		this(context,attrs,0);
	}
	
	public ScanView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		mScaned = BitmapFactory.decodeResource(context.getResources(), R.drawable.scan_scaned);
		mUnscan = BitmapFactory.decodeResource(context.getResources(), R.drawable.scan_unscan);
		mScanline = BitmapFactory.decodeResource(context.getResources(), R.drawable.scan_scanline);
		mPos = 0;
		mIsDown = true;
		mRect = new Rect(0, 0, mScaned.getWidth(),0);
		mIsEnd = false;
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		if(mIsEnd){
			canvas.drawBitmap(mScaned, 0, 0, null);
			return ;
		}
		canvas.drawBitmap(mUnscan, 0, 0, null);
		mRect.bottom = mPos+mScanline.getHeight()/2;
		canvas.drawBitmap(mScaned, mRect, mRect, null);
		canvas.drawBitmap(mScanline, 0, mPos, null);

		int bottom = mScaned.getHeight()-mScanline.getHeight(); 
		
		if(mIsDown){
			mPos +=STEP;
			if(mPos>=bottom){
				mPos = bottom;
				mIsDown = false;
			}
		}else{
			mPos -=STEP/2;
			if(mPos<=0){
				mPos = 0;
				mIsDown = true;
			}
		}
		postInvalidateDelayed(45);
	}
	
	public void scanEnd(){
		mIsEnd = true;
	}
	public void scanStart(){
	    mIsEnd = false;
	    mPos = 0;
	    postInvalidate();
	}

}
